﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using Me.Practice.ElevatorEngine.Domain.Entity;

namespace Me.Practice.ElevatorEngine.Infrastructure
{
	public class BuildingController
	{
		private readonly ReadOnlyCollection<ElevatorController> _elevatorControllers;
		private readonly ReadOnlyCollection<FloorController> _floorControllers;		
		
		public BuildingController(Building building)
		{
			ControlledBuilding = building;
			
			var elevatorControllers = building.Elevators.Select(elevator => new ElevatorController(elevator)).ToList();
		    _elevatorControllers = new ReadOnlyCollection<ElevatorController>(elevatorControllers);
			
			var floorControllers = building.Floors.Select(floor => new FloorController(floor)).ToList();
		    _floorControllers = new ReadOnlyCollection<FloorController>(floorControllers);
		}
		
		public Building ControlledBuilding { get; private set; }
		
		public IEnumerable<ElevatorController> ElevatorControllers
		{
			get
			{
				return _elevatorControllers;
			}
		}
		
		public IEnumerable<FloorController> FloorControllers
		{
			get
			{
				return _floorControllers;	
			}
		}
		
		public void ActivateElevator(string id)
		{			
			var elevatorController = 
				ElevatorControllers.Single(ec => ec.ControlledElevator.Id.Equals(id));

		    var elevatorControllerThread = 
                new Thread(elevatorController.ActivateElevator) {Name = id};

		    elevatorControllerThread.Start();
		}
		
		public void DeactivateElevator(string id)
		{			
			var elevatorController = 
				ElevatorControllers.Single(ec => ec.ControlledElevator.Id.Equals(id));
			
			elevatorController.DeactivateElevator();
		}
	}
}
